define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "UtilDir/loading",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock, Loading) {

    var getFxPopGDPController = function () {
        return getServer() + "/fxPopGDP";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initCreateProvince();
        createFieldInfoGrid();
        createFxPopGDPGrid();
    };
    var initCreateProvince = function () {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    };

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            createFxPopGDPGrid();
        });
        $("#btnReset").click(function () {
            $("#provinceSelect").val("");
            $("#citySelect").val("");
            $("#areaSelect").val("");
        });
    };
    var createFxPopGDPGrid = function () {
        $("#fxPopGDPGrid").datagrid({
            url: getFxPopGDPController() + "/queryFxPopGDP",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'province',
                    title: '省',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'city',
                    title: '市',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'area',
                    title: '区（县）',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'ls_GDP',
                    title: 'GDP(单位: 元)',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'ls_Pop',
                    title: '常住人口(单位: 人)',
                    width: '20%',
                    align: 'center',
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text:"导入",
                handler: function(){
                    importForm();
                    $("#qhFieldInfoLi").html("").append(fieldInfoGridDom.clone());
                    setTimeout(function () {
                        showFieldInfo();
                    }, 150);

                }
            }, {
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteFxPopGDP();
                }
            }],
            queryParams: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
    var deleteFxPopGDP = function () {
        var rows = $("#fxPopGDPGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxPopGDPController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxPopGDPGrid();
                }
            });
        }, function () {
            return;
        });

    };

    /**
     * 导入
     */
    var importForm = function () {
        var minList = [], nameList = [];
        // 获取文件名
        $("#uploadFile").on("change", function () {
            $("#commentInfo").val("");
            var uploadInputFiles = document.getElementById("uploadFile").files;
            minList = []; nameList = [];
            var text = "";
            for (var i = 0; i < uploadInputFiles.length; i++) {
                console.log("uploading: " + uploadInputFiles[i].name);
                text += uploadInputFiles[i].name + "\n";
                minList.push(uploadInputFiles[i].name.slice(uploadInputFiles[i].name.length - 3, uploadInputFiles[i].name.length));
                nameList.push(uploadInputFiles[i].name.split(".")[0]);
            }
            $("#commentInfo").val(text);
        });

        $("#uploadModal").modal();

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }else if(!judgeIsOnce(minList)){
                //Util.alert('上传数量限制:.dbf、.prj、.shp、.shx文件各1个;.sbn、.sbx、.shp.xml文件至多一个。');
                Util.alert('上传数量限制:需.dbf、.shp、.shx文件各1个。');
                minList = [];
                return;
            }else if(!judgeName(nameList)){
                Util.alert("文件名请保持一致！");
                nameList = [];
                return;
            }
            var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
            if(province == ""){
                Util.alert("请选择场地所在省份!");
                return;
            }
            /*if(city == ""){
                Util.alert("请选择场地所在市!");
                return;
            }
            if(area == ""){
                Util.alert("请选择场地所在区县!");
                return;
            }*/
            var formData = new FormData();
            for(var i = 0; i < uploadinput.files.length; i++){
                formData.append('files', uploadinput.files[i]);
            }
            formData.append("province", province);
            formData.append("city", city);
            formData.append("area", area);

            var gdpUnit = $("input[name='gdpUnit']:checked").val(), popUnit = $("input[name='popUnit']:checked").val();
            formData.append("gdpUnit", gdpUnit);
            formData.append("popUnit", popUnit);

            loading.show();
            $.ajax({
                url: getFxPopGDPController() + "/importShp",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    $("#commentInfo").val("");
                    loading.close();
                    Util.alert(data);
                    createFxPopGDPGrid();
                }
            });
        });
    };
    var judgeIsOnce = function (list) {
        // ["dbf","prj","shp","shx"];
        var dbf = 0;var prj = 0;var shp = 0;var shx = 0;var sbn = 0;var sbx = 0;var xml = 0;
        $.each(list,function (idx,item) {
            if(item == 'dbf') dbf++;
            if(item == 'prj') prj++;
            if(item == 'shp') shp++;
            if(item == 'shx') shx++;
            if(item == 'sbn') sbn++;
            if(item == 'sbx') sbx++;
            if(item == 'xml') xml++;
        })
        //if(dbf == 1 && prj == 1 && shp == 1 && shx == 1 && sbn < 2 && sbx < 2 && xml < 2) return true;
        if(dbf == 1 && prj < 2 && shp == 1 && shx == 1) return true;
        else return false;
    };
    var judgeName = function (list) {
        var name = list[0];
        var result = list.filter(function (item) {
            return item == name;
        })
        if(result.length == list.length) return true;
        else return false;
    };

    var showFieldInfo = function () {
        console.log("showFieldInfo")
        var data = [
            {"序号": "1", "数据类型": "varchar(45)", "是否必填": "否", "注释": "目标编号", "示例": "1306"},
            {"序号": "2", "数据类型": "varchar(45)", "是否必填": "否", "注释": "目标长度", "示例": "0.033"},
            {"序号": "3", "数据类型": "varchar(45)", "是否必填": "否", "注释": "目标面积", "示例": "6.94"},
            {"序号": "4", "数据类型": "varchar(45)", "是否必填": "是", "注释": "GDP", "示例": "6824043.52"},
            {"序号": "5", "数据类型": "varchar(45)", "是否必填": "否", "注释": "常住人口", "示例": "7832"},
        ];
        $("#qhFieldInfoGrid").datagrid({
            data: data,
            method: "GET",
            //fitColumns: true,
            autoRowHeight: false,
            idField: 'id',
            columns:[[
                //{field:"ck",checkbox:true},
                {
                    field:'序号',
                    title:'序号',
                    width:'10%',
                    align:'center',
                },
                {
                    field:'数据类型',
                    title:'数据类型',
                    width:'25%',
                    align:'center',

                },
                {
                    field:'是否必填',
                    title:'是否必填',
                    width:'15%',
                    align:'center',
                },
                {
                    field:'注释',
                    title:'注释',
                    width:'30%',
                    align:'center',
                },
                {
                    field:'示例',
                    title:'示例',
                    width:'24.2%',
                    align:'center',
                },
            ]],
            pagination: false,
            pageSize: 13
        });
    };
    var createFieldInfoGrid = function () {
        var parentDiv = $('<div></div>');
        parentDiv.attr('id','qhFieldInfo');
        parentDiv.css('z-index', "100000");
        parentDiv.css('width', "430px");
        var childDiv = $('<div></div>');
        childDiv.attr('id','qhFieldInfoGrid');
        parentDiv.append(childDiv);
        fieldInfoGridDom = parentDiv;
    };

    var loading = Loading({text : "正在上传数据..."}), fieldInfoGridDom;

    return {
        init: init
    };
});
